<template>
<#assign primaryKey = "id">
<#if tableColumnList??>
<#assign pkNumber = 0>
<#list tableColumnList as koiColumn>
<#if koiColumn.isPk == '0' && pkNumber == 0 >
<#assign pkNumber = pkNumber + 1>
<#assign primaryKey = koiColumn.javaField>
</#if>
</#list>
</#if>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId">
        <#if tableColumnList?exists>
        <#assign searchNumber = 0>
        <#list tableColumnList as koiColumn>
        <#if koiColumn.isSearch == '0'>
        <el-form-item label="${koiColumn.columnComment}" prop="${koiColumn.javaField}">
          <#if koiColumn.elementType == 'input'>
          <el-input
            placeholder="请输入${koiColumn.columnComment}"
            v-model="searchParams.${koiColumn.javaField}"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
          <#elseif koiColumn.elementType == 'select' && koiColumn.dictType?? && koiColumn.dictType != ''>
          <el-select
            placeholder="请选择${koiColumn.columnComment}"
            v-model="searchParams.${koiColumn.javaField}"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option
              v-for="koi in koiDicts.${koiColumn.dictType}"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
          <#elseif koiColumn.elementType == 'select' && koiColumn.dictType == ''>
          <!-- 下拉框需要字典类型，若没有，则只生成示例 -->
          <el-select
            placeholder="请选择${koiColumn.columnComment}"
            v-model="searchParams.${koiColumn.javaField}"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
          <#elseif koiColumn.elementType == 'datetime' && searchNumber == 0>
          <#assign searchNumber = searchNumber + 1>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            range-separator="至"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
          <#else>
          <el-input
            placeholder="请输入${koiColumn.columnComment}"
            v-model="searchParams.${koiColumn.javaField}"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
          </#if>
        </el-form-item>
        </#if>
        </#list>
        </#if>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['${moduleFolder}:${pageFolder}:search']">搜索</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['${moduleFolder}:${pageFolder}:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['${moduleFolder}:${pageFolder}:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['${moduleFolder}:${pageFolder}:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟🌻"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <#if tableColumnList??>
        <#assign tableNumber = 0>
        <#list tableColumnList as koiColumn>
        <#if koiColumn.isList == '0'>
        <#if koiColumn.isPk == '0' && tableNumber == 0 >
        <#assign tableNumber = tableNumber + 1>
        <el-table-column label="序号" prop="${koiColumn.javaField}" width="80px" align="center" type="index"></el-table-column>
        <#elseif koiColumn.dictType != ''>
        <el-table-column label="${koiColumn.columnComment}" prop="${koiColumn.javaField}" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.${koiColumn.dictType}" :value="scope.row.${koiColumn.javaField}"></KoiTag>
          </template>
        </el-table-column>
        <#elseif koiColumn.columnType == 'datetime'>
        <el-table-column label="${koiColumn.columnComment}" prop="${koiColumn.javaField}" width="180px" align="center"></el-table-column>
        <#else>
        <el-table-column
          label="${koiColumn.columnComment}"
          prop="${koiColumn.javaField}"
          width="120px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        </#if>
        </#if>
        </#list>
        </#if>
        <el-table-column label="操作" align="center" width="120" fixed="right" v-auth="['${moduleFolder}:${pageFolder}:update', '${moduleFolder}:${pageFolder}:delete']">
          <template #default="{ row }">
            <el-tooltip content="修改🌻" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['${moduleFolder}:${pageFolder}:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除🌻" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['${moduleFolder}:${pageFolder}:delete']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
            <#if tableColumnList??>
            <#assign tableNumber = 0>
            <#list tableColumnList as koiColumn>
            <#if koiColumn.isForm == '0'>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="${koiColumn.columnComment}" prop="${koiColumn.javaField}">
                  <#if koiColumn.elementType == 'number'>
                  <el-input-number v-model="form.${koiColumn.javaField}" placeholder="请输入数字" :min="1" clearable />
                  <#elseif koiColumn.elementType == 'select' && koiColumn.dictType?? && koiColumn.dictType != ''>
                  <el-select placeholder="请选择${koiColumn.columnComment}" v-model="form.${koiColumn.javaField}" clearable>
                    <el-option
                      v-for="koi in koiDicts.${koiColumn.dictType}"
                      :key="koi.dictValue"
                      :label="koi.dictLabel"
                      :value="koi.dictValue"
                    />
                  </el-select>
                  <#elseif koiColumn.elementType == 'select' && koiColumn.dictType == ''>
                  <!-- 下拉框需要字典类型，若没有，则只生成示例 -->
                  <el-select placeholder="请选择${koiColumn.columnComment}" v-model="form.${koiColumn.javaField}" clearable>
                    <el-option label="启用" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                  <#elseif koiColumn.elementType == 'radio' && koiColumn.dictType?? && koiColumn.dictType != ''>
                  <el-radio-group v-model="form.${koiColumn.javaField}">
                    <el-radio
                      border
                      v-for="koi in koiDicts.${koiColumn.dictType}"
                      :key="koi.dictValue"
                      :label="koi.dictValue"
                    >{{ koi.dictLabel }}
                    </el-radio>
                  </el-radio-group>
                  <#elseif koiColumn.elementType == 'radio' && koiColumn.dictType == ''>
                  <!-- 单选框需要字典类型，若没有，则只生成示例 -->
                  <el-radio-group v-model="form.${koiColumn.javaField}">
                    <el-radio border label="0">启用</el-radio>
                    <el-radio border label="1">停用</el-radio>
                  </el-radio-group>
                  <#elseif koiColumn.elementType == 'checkbox' && koiColumn.dictType?? && koiColumn.dictType != ''>
                  <el-checkbox-group v-model="form.${koiColumn.javaField}">
                    <el-checkbox
                      border
                      v-for="koi in koiDicts.${koiColumn.dictType}"
                      :key="koi.dictValue"
                      :label="koi.${koiColumn.javaField}"
                    >{{ koi.dictLabel }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <#elseif koiColumn.elementType == 'checkbox' && koiColumn.dictType == ''>
                  <!-- 多选框需要字典类型，若没有，则只生成示例 -->
                  <el-checkbox-group v-model="form.${koiColumn.javaField}">
                    <el-checkbox border label="吃饭" />
                    <el-checkbox border label="睡觉" />
                    <el-checkbox border label="打游戏" />
                  </el-checkbox-group>
                  <#elseif koiColumn.columnType == 'date'>
                  <el-date-picker
                    v-model="form.${koiColumn.javaField}"
                    type="date"
                    placeholder="请选择日期"
                  />
                  <#elseif koiColumn.columnType == 'datetime'>
                  <el-date-picker
                    v-model="form.${koiColumn.javaField}"
                    type="datetime"
                    placeholder="请选择日期时间"
                  />
                  <#elseif koiColumn.elementType == 'textarea'>
                  <el-input
                    type="textarea"
                    v-model="form.${koiColumn.javaField}"
                    :rows="3"
                    placeholder="请输入${koiColumn.columnComment}"
                    clearable
                  />
                  <#else>
                  <el-input v-model="form.${koiColumn.javaField}" placeholder="请输入${koiColumn.columnComment}" clearable />
                  </#if>
                </el-form-item>
              </el-col>
            </#if>
            </#list>
            </#if>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="${tableAuth}Page">
import { ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgSuccess, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
import { listPage, getById, add, update, deleteById, batchDelete } from "@/api/${moduleFolder}/${pageFolder}/index.ts";
<#if tableColumnList?exists>
<#assign datePickerNeeded = 0>
<#assign koiDictNeeded = 0>
<#list tableColumnList as koiColumn>
<#if koiColumn.isSearch == "0"  &&  koiColumn.javaType == "Date">
<#assign datePickerNeeded = datePickerNeeded + 1>
</#if>
<#if koiColumn.dictType != "">
<#assign koiDictNeeded = koiDictNeeded + 1>
</#if>
</#list>
<#if datePickerNeeded != 0>
import { koiDatePicker } from "@/utils/index.ts";
const dateRange = ref();
</#if>
<#if koiDictNeeded != 0>
import { useKoiDict } from "@/hooks/dicts/index.ts";
</#if>
</#if>

<#if tableColumnList?exists>
<#assign dictTypes = "">
<#list tableColumnList as koiColumn>
<#if koiColumn.dictType != "">
<#if dictTypes?length != 0>
<#assign dictTypes = dictTypes + ",">
</#if>
<#assign dictTypes = dictTypes + '"' + koiColumn.dictType + '"'>
</#if>
</#list>
<#if dictTypes != "">
const { koiDicts } = useKoiDict([${dictTypes}]);
</#if>
</#if>
// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
<#if tableColumnList?exists>
<#list tableColumnList as koiColumn>
<#if koiColumn.isSearch == '0'>
  ${koiColumn.javaField}: "",
</#if>
</#list>
</#if>
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
<#if tableColumnList?exists>
<#list tableColumnList as koiColumn>
<#if koiColumn.isSearch == '0'>
    ${koiColumn.javaField}: "",
</#if>
</#list>
</#if>
  };
  <#if tableColumnList?exists>
  <#assign datePickerNeeded = false>
  <#list tableColumnList as koiColumn>
  <#if koiColumn.isSearch == "0"  &&  koiColumn.javaType == "Date">
  <#assign datePickerNeeded = true>
  </#if>
  </#list>
  <#if datePickerNeeded>
  dateRange.value = [];
  </#if>
  </#if>
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
<#if tableColumnList?exists>
<#assign dateRangeNeeded = false>
<#list tableColumnList as koiColumn>
<#if koiColumn.isSearch == "0"  &&  koiColumn.javaType == "Date">
<#assign dateRangeNeeded = true>
</#if>
</#list>
<#if datePickerNeeded>
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
<#else>
    const res: any = await listPage(searchParams.value);
</#if>
</#if>
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
<#if tableColumnList?exists>
<#assign dateRangeNeeded = false>
<#list tableColumnList as koiColumn>
<#if koiColumn.isSearch == "0"  &&  koiColumn.javaType == "Date">
<#assign dateRangeNeeded = true>
</#if>
</#list>
<#if datePickerNeeded>
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
<#else>
    const res: any = await listPage(searchParams.value);
</#if>
</#if>
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

// 获取数据表格数据
onMounted(() => {
  handleListPage();
});

const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.${primaryKey});
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "添加操作";
  koiDrawerRef.value.koiOpen();
  koiMsgInfo("添加🌻");
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据🌻");
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试🌻");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改操作";
  const id = row ? row.${primaryKey} : ids.value[0];
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据🌻");
  }
  // 回显数据
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
  koiMsgInfo("修改🌻");
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("${tableComment}");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
<#if tableColumnList?exists>
<#list tableColumnList as koiColumn>
<#if koiColumn.isForm == '0'>
  ${koiColumn.javaField}: null<#sep>,</#sep>
</#if>
</#list>
</#if>
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
<#if tableColumnList?exists>
<#list tableColumnList as koiColumn>
<#if koiColumn.isForm == '0'>
    ${koiColumn.javaField}: null<#sep>,</#sep>
</#if>
</#list>
</#if>
  };
};

/** 表单规则 */
const rules = reactive({
<#if tableColumnList?exists>
<#list tableColumnList as koiColumn>
<#if koiColumn.isRule == '0'>
  ${koiColumn.javaField}: [{ required: true, message: "请输入${koiColumn.columnComment}", trigger: "blur" }]<#sep>,</#sep>
</#if>
</#list>
</#if>
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.${primaryKey} != null && form.value.${primaryKey} != "") {
        try {
          await update(form.value);
          koiMsgSuccess("修改成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试🌻");
        }
      } else {
        try {
          await add(form.value);
          koiMsgSuccess("添加成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试🌻");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容🌻");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.${primaryKey};
  if (id == null || id == "") {
    koiMsgWarning("请选中需要删除的数据🌻");
    return;
  }
  koiMsgBox("您确认删除该数据么？删除后将无法进行恢复？")
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiNoticeSuccess("删除成功🌻");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("删除失败，请刷新重试🌻");
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据🌻");
    return;
  }
  koiMsgBox("您确认进行批量删除么？删除后将无法进行恢复？")
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiNoticeSuccess("批量删除成功🌻");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("批量删除失败，请刷新重试🌻");
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};
</script>

<style lang="scss" scoped></style>
